// me/mongoose/exercise/demo1_quickstart.js

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
});

const kittySchema = mongoose.Schema({
    name: String
});

// const Kitten = mongoose.model('Kitten', kittySchema);

// const felyne = new Kitten({ name: 'Felyne' });
// console.log(felyne.name); // 'Felyne'

// 译者注：注意了， method 是给 document 用的
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
    const greeting = this.name
        ? "Meow name is " + this.name
        : "I don't have a name";
    console.log(greeting);
}

const Kitten = mongoose.model('Kitten', kittySchema);

const fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"

function save() {
    fluffy.save(function (err, fluffy) {
        if (err) return console.error(err);
        fluffy.speak();
    });
}

// save();

Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    console.log(kittens);
})

Kitten.find({ name: /^fluff/ }, (err, data) => {
    if (err) return console.error(err);
    console.log(data);
});

// 
// setTimeout(() => { db.close(); }, 1000);

